<template>
  <el-scrollbar height="100vh">
    <div class="container">
      <el-affix :offset="1">
        <h1 class="title">切换地图容器 getTarget/setTarget</h1>
      </el-affix>
      <div id="map1" class="map-x"></div>
      <el-button type="success" round @click="tabContainer()" style="margin: 10px 0;">点击切换视图容器</el-button>
      <div id="map2" class="map-x"></div>
      <div class="codestyle"><Code /></div>
      <dl>
        <p>方法：</p>
        <dt>getTarget：获取当前地图容器id值</dt>
        <dt>setTarget：设置地图容器，填写id值</dt>
      </dl>
    </div>
  </el-scrollbar>
</template>
<script>
import { onMounted, ref } from 'vue-demi'
import Code from './code.vue'
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ' // 引入XYZ地图格式
export default {
  setup () {
    const map1 = ref(null)

    const init = () => {
      map1.value = new Map({
        layers: [
          new Tile({
            source: new XYZ({
              url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
            })
          })
        ],
        view: new View({
          // 地图视图
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [116.41400, 39.91500], // 北京坐标
          zoom: 8
        })
      })
      map1.value.setTarget('map1')
    }

    const tabContainer = () => {
      // 获取当前地图容器，并进行判断
      const target = map1.value.getTarget() === 'map1' ? 'map2' : 'map1'

      // 重新设置地图容器
      map1.value.setTarget(target)
    }

    onMounted(() => {
      init()
    })
    return {
      map1,
      tabContainer
    }
  },
  components: {
    Code
  }
}
</script>
<style lang="scss" scoped>
@import '../../css/main.scss';
</style>
